package com.jsonal.common;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;

/**
 * 文件操作
 *
 * @author ruopeng.cheng
 * @version 1.0
 * @date 2018-7-20 09:08:40
 */
public class FileUtil {


    /**
     * 生成缩略图
     *
     * @param localImagePath     路径
     * @param thumbnailImagePath 缩略图路径
     * @param width              宽
     * @throws IOException          异常
     */
    public static void createThumbnailImage(String localImagePath, String thumbnailImagePath, int width) throws IOException {

        int height = 0;
        File localImage = new File(localImagePath);
        try {


            Image imageSrc = ImageIO.read(localImage);
            int w = imageSrc.getWidth(null);
            int h = imageSrc.getHeight(null);
            height = width * h / w;

            //判断目标文件所在的目录是否存在 ，如果不存在则新建
            File thumbnailFile = new File(thumbnailImagePath);
            if (!thumbnailFile.getParentFile().exists()) {

                if (!thumbnailFile.getParentFile().mkdirs()) {

                    throw new IOException("创建目标文件所在目录失败！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Thumbnails.of(localImage).size(width,height).toFile(thumbnailImagePath);
    }


}
